package com.jse.api;

import java.net.http.HttpClient.Version;
import java.security.MessageDigest;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.http.HttpResponse;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.jse.Http;
import com.jse.IP;
import com.jse.Lang;
import com.jse.Log;
import com.jse.Times;
import com.jse.json.JsonObject;

public class WxPay {
	private static Log log = Log.get(WxPay.class);

	/**
	 * 
	 * @param param title id orderno price openid
	 * @return
	 */
	public static Map<Object,Object> h5(Map<String, Object> data) {
		JsonObject param=new JsonObject(data);
		String appid = param.getString("appid");
		String mch_id = param.getString("mch_id");// 商户号
		String key = param.getString("key");
		String openid = param.getString("openid");// openid 用户微信id
		String body = param.getString("title");
		String out_trade_no = param.getString("orderno");// 订单号
		String attach = param.getString("id");// 附加数据 原样返回
		String totalFee = getMoney(param.getString("price"));// 总金额以分为单位，不带小数点
		String spbill_create_ip = IP.ip();// 订单生成的机器 IP
		String notify_url = param.get("notify_url").toString();// 通知
		String trade_type = "JSAPI";
		String nonce_str = generateNonceStr();// 随机字符串
		
		try {
			SortedMap<String, String> packageParams = new TreeMap<String, String>();
			packageParams.put("appid", appid);
			packageParams.put("mch_id", mch_id);
			packageParams.put("nonce_str", nonce_str);
			packageParams.put("body", body);
			packageParams.put("attach", attach);
			packageParams.put("out_trade_no", out_trade_no);
			packageParams.put("total_fee", totalFee);
			packageParams.put("spbill_create_ip", spbill_create_ip);
			packageParams.put("notify_url", notify_url);
			packageParams.put("trade_type", trade_type);
			packageParams.put("openid", openid);
			String sign = generateSignature(packageParams, key,"MD5");
			packageParams.put("sign", sign);// 加密
			String requestXML = generateSignedXml(packageParams, key,"MD5");
			log.info("支付请求：" + requestXML);
			String resXml = Http.postXml("https://api.mch.weixin.qq.com/pay/unifiedorder",requestXML);
			log.info("支付结果：" + resXml);
			Map<String, String> map = xmlToMap(resXml);
			SortedMap<Object,Object> ret = new TreeMap<Object,Object>();
			ret.put("appId", appid);
			ret.put("timeStamp", getCurrentTimestamp());
			ret.put("nonceStr", map.get("nonce_str"));
			ret.put("package", "prepay_id=" + map.get("prepay_id"));
			ret.put("signType", "MD5");
			String signStr=createSign(ret,key);
			ret.put("paySign", signStr);
			return ret;
		} catch (Exception e) {
			log.warn("微信h5支付生成失败!err:%s", e);
		}
		return null;
	}

	/**
	 * 获取扫描支付url
	 * 
	 * @param map{
	 *            title id orderno price
	 *            notify_url 通知地址 product_id 商品id }
	 * @return
	 */
	public static String qrcode(HashMap<String, Object> data) {
		JsonObject param=new JsonObject(data);
		String appid = param.get("appid").toString();
		String mch_id = param.get("mch_id").toString();// 商户号
		String key = param.get("key").toString();
		String notify_url = param.get("notify_url").toString();// 通知
		String body = param.getString("title");
		String out_trade_no = param.getString("orderno");// 订单号
		String nonce_str = generateNonceStr();// 随机字符串
		String product_id = param.getString("id");// 商品id 扫描必填
		String spbill_create_ip = IP.ip();
		String totalFee = getMoney(param.getString("price"));// 总金额以分为单位，不带小数点
		try {

			// 正式上线的时候价格根据订单id查询
//			String order_price = "1"; // 价格 注意：价格的单位是分
			SortedMap<String, String> packageParams = new TreeMap<String, String>();
			packageParams.put("appid", appid);
			packageParams.put("mch_id", mch_id);
			packageParams.put("nonce_str", nonce_str);
			packageParams.put("body", body);
			packageParams.put("out_trade_no", out_trade_no);
			packageParams.put("total_fee", totalFee);
			packageParams.put("spbill_create_ip", spbill_create_ip);
			packageParams.put("notify_url", notify_url);
			packageParams.put("trade_type", "NATIVE");
			packageParams.put("product_id", product_id);// 商品id
			Calendar nowTime = Calendar.getInstance();
			packageParams.put("time_start", Times.format("yyyyMMddHHmmss", nowTime.getTime()));
			nowTime.add(Calendar.DATE, 1);
			packageParams.put("time_expire", Times.format("yyyyMMddHHmmss", nowTime.getTime()));

			String sign = generateSignature(packageParams, key,"MD5");
			packageParams.put("sign", sign);// 加密

			String requestXML = generateSignedXml(packageParams, key,"MD5");
			log.info("支付请求：" + requestXML);
			Object res = Http.send(Version.HTTP_1_1,
					"POST","https://api.mch.weixin.qq.com/pay/unifiedorder",
					requestXML,15000,Map.of("Content-Type","application/xml"),false,null);//"application/xml"
			String resXml="";
			if(res instanceof HttpResponse<?> resp) {
				resXml= resp.body().toString();
			}
			log.info("支付结果：" + resXml);
			Map<String, String> map = xmlToMap(resXml);
			// 交易保障
			String codeurl = "";
			if (map.get("return_code").toString().equals("SUCCESS")
					&& map.get("result_code").toString().equals("SUCCESS")) {
				codeurl = map.get("code_url");// 微信二维码短链接

			} else {
				log.info(map.get("err_code_des"));
			}
			return codeurl;
		} catch (Exception e) {
			log.warn("微信支付二维码生成失败!err:%s", e);
		}
		return "";
	}
	
	/**
	 * 元转换成分
	 * 
	 * @param money
	 * @return
	 */
	public static String getMoney(String amount) {
		if (amount == null) {
			return "";
		}
		// 金额转化为分为单位
		String currency = amount.replaceAll("\\$|\\￥|\\,", ""); // 处理包含, ￥ 或者$的金额
		int index = currency.indexOf(".");
		int length = currency.length();
		Long amLong = 0l;
		if (index == -1) {
			amLong = Long.valueOf(currency + "00");
		} else if (length - index >= 3) {
			amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
		} else if (length - index == 2) {
			amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
		} else {
			amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
		}
		return amLong.toString();
	}
	
	@SuppressWarnings("rawtypes")
	public static String createSign(SortedMap<Object,Object> parameters,String key){  
        StringBuffer sb = new StringBuffer();  
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）  
        Iterator it = es.iterator();  
        while(it.hasNext()) {  
            Map.Entry entry = (Map.Entry)it.next();  
            String k = (String)entry.getKey();  
            Object v = entry.getValue();  
            if(null != v && !"".equals(v)   
                    && !"sign".equals(k) && !"key".equals(k)) {  
                sb.append(k + "=" + v + "&");  
            }  
        }  
        sb.append("key=" + key);
        String sign = Lang.md5(sb.toString()).toUpperCase();  
        return sign;  
    }
	
	/**
     * 获取当前时间戳，单位秒
     * @return
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis()/1000;
    }
    
    public static String generateSignature(final Map<String, String> data, String key, String signType) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals("sign")) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        if ("MD5".equals(signType)) {
            return MD5(sb.toString()).toUpperCase();
        }
        else if ("HmacSHA256".equals(signType)) {
            return HMACSHA256(sb.toString(), key);
        }
        else {
            throw new Exception(String.format("Invalid sign_type: %s", signType));
        }
    }
    public static String generateSignedXml(final Map<String, String> data, String key, String signType) throws Exception {
        String sign = generateSignature(data, key, signType);
        data.put("sign", sign);
        return mapToXml(data);
    }
    public static String MD5(String data) throws Exception {
        java.security.MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
    public static String HMACSHA256(String data, String key) throws Exception {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        byte[] array = sha256_HMAC.doFinal(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
    
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<String, String>();
            DocumentBuilder documentBuilder = newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
            org.w3c.dom.Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
                // do nothing
            }
            return data;
        } catch (Exception ex) {
        	Log.get("WXPayUtil").warn("Invalid XML, can not convert to map. Error message: {}. XML content: {}", ex.getMessage(), strXML);
            throw ex;
        }

    }
    
    public static String mapToXml(Map<String, String> data) throws Exception {
        org.w3c.dom.Document document = newDocumentBuilder().newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: data.keySet()) {
            String value = data.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString(); //.replaceAll("\n|\r", "");
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    }
    
    public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        documentBuilderFactory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);
        return documentBuilderFactory.newDocumentBuilder();
    }
    public static String generateNonceStr() {
        return Lang.uuid();
    }
	
	public static void main(String[] args) {
		var tab=new JsonObject();
		tab.put("appid","wx2787c3302c182d65");
		tab.put("mch_id","1289729501");
		tab.put("key","6e332d87778242619fd832c1bc85d12f");
		tab.put("notify_url","https://www.iepsy.com/pay/wx/notify");
		tab.put("openid","oHStSsw7owoEDUrWloxO1mNW9bFc");
		tab.put("title","xxxx");
		tab.put("id",28101);
		var _orderno = "20240703193601958126159"+"-"+System.currentTimeMillis();
		if(_orderno.length() > 32){
			_orderno=_orderno.substring(0,32);
		}
		tab.put("orderno",_orderno);
		tab.put("price",0.01);
		//tab.put("url",res)
		//tab.put("timeStamp",java.lang.Long.toString(System.currentTimeMillis()/1000))
		//tab.put("nonceStr",Lang.uuid())
		//tab.put("package")
		//tab.put("signType","RSA")
		//tab.put("paySign",sign)
		//print("tab:"+tab)
		var res=com.jse.api.WxPay.h5(tab);
		System.out.println(res);
	}
}
